<template>
    <div class="container">
        <!-- 导航栏区域开始 -->
        <TridentNavBar>
            <template #left><i class="iconfont icon-zuojiantou"></i></template>
            <template #default>聊天信息</template>
            <template #right><i class="iconfont icon-home" @click="$router.push('/')"></i></template>
        </TridentNavBar>
        <!-- 导航栏区域结束 -->

        <!-- 头部信息区域开始 -->
        <div class="user-wrap" v-if="groupChat || friend">
            <!-- 好友骨架屏区域 -->
            <TridentFriendSkeleton v-if="route.query.mode == '1' && isSkeleton" />

            <!-- 好友骨架屏区域 -->
            <TridentFriendSkeleton v-if="route.query.mode == '2' && isSkeleton" v-for="(index) in 3" :key="index"/>

            <!-- 好友 -->
            <div class="item-box" v-if="friend">
                <div class="avatar">
                    <van-image
                        width="60"
                        height="60"
                        :src="friend.info.avatar_url ? global.MINIO_FILE_DOMAIN + friend.info.avatar_url : 'src/assets/images/default_avatar.png'"
                        fit="contain"
                    />
                </div>
                <div class="username ellipsis-1">{{ friend.info.username }}</div>
            </div>

            <!-- 群聊成员 -->
            <div class="item-box" v-for="(item, index) in groupChat?.member" :key="index">
                <div class="avatar">
                    <van-image
                        width="60"
                        height="60"
                        :src="item.avatar_url ? global.MINIO_FILE_DOMAIN + item.avatar_url : 'src/assets/images/default_avatar.png'"
                        fit="contain"
                    />
                </div>
                <div class="username ellipsis-1">{{ item.username }}</div>
            </div>

            <!-- 添加群成员按钮 -->
            <div class="item-box" @click="$router.push('/contact?gid=' + route.query.gid)" v-if="route.query.mode == '2' && admin?.uid == userStore.profile.user.uid">
                <div class="top"><i class="iconfont icon-jia"></i></div>
            </div>

            <!-- 移除群成员按钮 -->
            <div class="item-box" @click="$router.push('/member?gid=' + route.query.gid)" v-if="route.query.mode == '2' && admin?.uid == userStore.profile.user.uid">
                <div class="top"><i class="iconfont icon-jian"></i></div>
            </div>
        </div>
        <!-- 头部信息区域结束 -->

        <!-- 群聊相关面板区域开始 -->
         <div class="group-wrap" v-if="route.query.mode == '2'">
            <!-- 群聊名称 -->
            <TridentCellItem :item="{title: '群聊名称', value: groupChat?.name}" position="right" @click="namePopup = true"/>

            <!-- 是否管理员 -->
            <TridentCellItem :item="{title: '管理员', value: admin?.username}" position="right" :is_arrows="false"/>

            <!-- 群二维码 -->
            <TridentCellItem :item="{title: '群二维码'}" @click="handleShowQrcode"/>
            
            <!-- 群公告 -->
            <TridentCellItem :item="{title: '群公告'}" @click="$router.push('/notice?gid=' + groupChat.id)"/>
            
            <!-- 备注 -->
            <TridentCellItem :item="{title: '备注', value: groupChat?.note}" :is_arrows="false" position="right"/>


            <!-- 我在群里的用户名 -->
            <TridentCellItem :item="{title: '我在群里的用户名', value: userStore.profile.user.username}" position="right"/>
            
            <!-- 显示群成员用户名 -->
            <!-- <TridentCellItem :item="{title: '显示群成员用户名'}"/> -->
         </div>
        <!-- 群聊相关面板区域结束 -->

        <!-- 查询聊天记录开始 -->
        <div class="search-record-wrap">
            <TridentCellItem :item="{title: '查询聊天记录'}" @click="$router.push('/record?mode=' + $route.query.mode + '&to_uid=' + friend?.info.uid)" v-if="$route.query.mode == '1'"/>
            <TridentCellItem :item="{title: '查询聊天记录'}" @click="$router.push('/record?mode=' + $route.query.mode + '&to_uid=' + groupChat.id)" v-else/>
        </div>
        <!-- 查询聊天记录结束 -->

        <!-- 操作区域开始 -->
        <div class="operate-wrap">
            <!-- 消息免打扰 -->
            <div class="operate-item">
                <div class="left">消息免打扰</div>
                <div class="right">
                    <van-switch v-model="isDisturb" active-color="#27BA9B" inactive-color="#dcdee0" size="18px" @change="handleDisturb"/>
                </div>
            </div>

            <!-- 置顶聊天 -->
            <div class="operate-item">
                <div class="left">置顶聊天</div>
                <div class="right">
                    <van-switch v-model="isTop" active-color="#27BA9B" inactive-color="#dcdee0" size="18px" @change="handleTop"/>
                </div>
            </div>

            <!-- 提醒 -->
            <div class="operate-item">
                <div class="left">提醒</div>
                <div class="right">
                    <van-switch active-color="#27BA9B" inactive-color="#dcdee0" size="18px" />
                </div>
            </div>
        </div>
        <!-- 操作区域结束 -->


        <!-- 清空聊天记录开始 -->
        <div class="clear-record-wrap" @click="handleClearChatRecord">
            <TridentCellItem :item="{title: '清空聊天记录'}"/>
        </div>
        <!-- 清空聊天记录结束 -->

        <!-- 投诉区域开始 -->
        <div class="complaint-wrap">
            <TridentCellItem :item="{title: '投诉'}"/>
        </div>
        <!-- 投诉区域结束 -->

        <!-- 退出群聊区域 -->
        <div class="logout-group-wrap"
            v-if="route.query.mode == '2' && admin?.uid == userStore.profile.user.uid"
            @click="handleShowTransferAdmin"
        >转让管理员</div>

        <div class="logout-group-wrap"
            v-if="route.query.mode == '2' && admin?.uid == userStore.profile.user.uid"
            @click="handleDissolveGroupChat"
        >解散群聊</div>

        <div class="logout-group-wrap"
            v-if="route.query.mode == '2' && admin?.uid != userStore.profile.user.uid" 
            @click="handleLogoutGroupChat"
        >退出群聊</div>

        <!-- 编辑群名弹层开始 -->
        <van-popup
            v-model:show="namePopup"
            position="bottom"
            closeable
            round
            :style="{ height: '20%' }"
        >
            <div class="popup-wrap">
                <div class="title-box">编辑群聊名称</div>
                <van-field v-model="editParams.name" label="群聊名称" placeholder="请输入群聊名称" />
                <div class="btn-box">
                    <van-button block color="#27BA9B" type="primary" size="small" @click="handleEditName">保存</van-button>
                </div>
            </div>
        </van-popup>
        <!-- 编辑群名弹层结束 -->


        <!-- 群二维码弹层开始 -->
        <van-popup
            v-model:show="qrcodePopup"
            position="bottom"
            closeable
            round
            :style="{ height: '40%' }"
        >
            <div class="popup-wrap">
                <div class="title-box">群二维码</div>
                <div class="btn-box">
                    <QRCodeVue
                        :value="qrCodeText"
                        :size="200"
                        :level="'H'"
                        :includeMargin="true"
                    />
                </div>
            </div>
        </van-popup>
        <!-- 编二维码弹层结束 -->

        <!-- 转让管理员弹层开始 -->
        <van-popup
            v-model:show="transferPopup"
            position="bottom"
            closeable
            round
            :close-on-click-overlay="false"
            :style="{ height: '80%' }"
        >
            <div class="popup-wrap">
                <div class="member-title-box">选择管理员</div>
                <div class="member-box">
                    <div class="member" v-for="(item, index) in candidateMemberList" :key="index" @click="handleCheckMember(item)">
                        <i class="iconfont icon-weixuanzhong" v-if="item.is_admin == 0"></i>
                        <i class="iconfont icon-xuanzhong" v-else></i>
                        <div class="avatar">
                            <van-image
                                width="50"
                                height="50"
                                :src="item.avatar_url ? global.MINIO_FILE_DOMAIN + item.avatar_url : 'src/assets/images/default_avatar.png'"
                                fit="contain"
                            />
                        </div>

                        <div class="username">{{ item.username }}</div>
                    </div>
                </div>
                <div class="member-btn-box">
                    <van-button style="margin-right: 15px;" color="#bbb" @click="handleCancel">取 消</van-button>

                    <van-button color="#27BA9B" type="primary" @click="handleConfirm">确 认</van-button>
                </div>
            </div>
        </van-popup>
        <!-- 转让管理员弹层结束 -->
    </div>
</template>

<script lang="ts" setup>
import { reqDissolveAPI, reqEditGroupChatAPI, reqGroupChatDetailAPI, reqGroupChatDisturbAPI, reqGroupChatTopAPI, reqRemoveMemberAPI, reqTransferAdminAPI } from '@/apis/groupChat'
import { useUserStore } from '@/store/modules/user'
import type { EditGroupChatParams, GroupChat, Member } from '@/types/groupChat'
import { showConfirmDialog, showSuccessToast, showToast } from 'vant'
import { inject, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import QRCodeVue from 'qrcode.vue'
import type { Friend } from '@/types/friend'
import { reqDisturbAPI, reqFriendDetailAPI, reqTopAPI } from '@/apis/friend'

// ----------------- 定义全局变量开始 -----------------
// 全局属性
const global: any = inject('global')

// 路由器
const router = useRouter()

// 路由
const route = useRoute()

console.log('参数 mode =', route.query.mode);
console.log('参数 id =', route.query.id);
console.log('参数 gid =', route.query.gid);

// 用户存储
const userStore = useUserStore()

// 骨架屏
const isSkeleton = ref<boolean>(false)
// ----------------- 定义全局变量结束 -----------------



// 挂载完成
onMounted(async() => {
    if (route.query.mode == '1') {
        await getFriend()
    } else {
        await getGroupChatInfo()
        editParams.value.name = groupChat.value?.name
    }
})



// ------------------ 清空聊天记录开始 ------------------
const handleClearChatRecord = () => {
    showConfirmDialog({
        message: '确定删除和农夫大兔子老婆的聊天记录吗?',
        confirmButtonColor: '#27BA9B'
    })
    .then(() => {
        // on confirm
    })
    .catch(() => {
        // on cancel
    });
}
// ------------------ 清空聊天记录结束 ------------------



// ------------------ 处理好友信息开始 ------------------
// 是否免打扰
const isDisturb = ref<boolean>(false)

// 是否置顶
const isTop = ref<boolean>(false)

const friend = ref<Friend>()
const getFriend = async () => {
    isSkeleton.value = true
    const result = await reqFriendDetailAPI(route.query.id as never)
    friend.value = result.data
    friend.value?.information.forEach((item) => {
        if (item.uid != userStore.profile.user.uid) {
            isDisturb.value = item.is_disturb == 1 ? true : false
            isTop.value = item.is_top == 1 ? true : false
        }
    })
    isSkeleton.value = false
}
// ------------------ 处理好友信息结束 ------------------



// ------------------ 处理退出群聊开始 ------------------
const handleLogoutGroupChat = () => {
    if (admin.value?.uid == userStore.profile.user.uid) {
        showToast('管理员退群,请先转让管理权限')
        return false
    }
    showConfirmDialog({
        message: '确定要退出群聊吗?',
        confirmButtonColor: '#27BA9B'
    })
    .then(async() => {
        await reqRemoveMemberAPI({gid: route.query.gid as never, uids: userStore.profile.user.uid})
        showSuccessToast('退出群聊成功')
        setTimeout(() => {
            router.push('/')
        }, 1000)
    })
    .catch(() => {
        // on cancel
    });
}
// ------------------ 处理退出群聊结束 ------------------



// ------------------ 处理解散群聊开始 ------------------
const handleDissolveGroupChat = () => {
    if (admin.value?.uid != userStore.profile.user.uid) {
        showToast('管理员才能解散群聊')
        return false
    }
    showConfirmDialog({
        message: '确定要解散群聊吗?',
        confirmButtonColor: '#27BA9B'
    })
    .then(async() => {
        await reqDissolveAPI(groupChat.value.id);
        showSuccessToast('解散群聊成功')
        setTimeout(() => {
            router.push('/')
        }, 1000)
    })
    .catch(() => {
        // on cancel
    })
}
// ------------------ 处理解散群聊结束 ------------------



// ------------------ 处理群聊信息开始 ------------------
// 管理员
const admin = ref<Member>()

// 群聊信息
const groupChat = ref<GroupChat>({
    id: 0,
    name: '',
    member: [],
    note: '',
    update_time: '',
    create_time: ''
})

// 获取群聊信息
const getGroupChatInfo = async () => {
    isSkeleton.value = true
    const result = await reqGroupChatDetailAPI(route.query.gid as never)
    groupChat.value = result.data
    groupChat.value.member.forEach((item: Member) => {
        // 判断免打扰 + 置顶
        if (item.uid == userStore.profile.user.uid) {
            isDisturb.value = item.is_disturb == 1 ? true : false
            isTop.value = item.is_top == 1 ? true : false
        }

        // 判断是否群聊管理员
        if (item.is_admin == 1) {
            admin.value = item
        } else {
            // 转让管理员，候选成员列表
            candidateMemberList.value.push({
                uid: item.uid,
                username: item.username,
                avatar_url: item.avatar_url,
                mobile: item.mobile,
                is_admin: 0
            })
        }
    })
    isSkeleton.value = false
}
// ------------------ 处理群聊信息结束 ------------------



// ------------------ 处理编辑群名开始 ------------------
// 编辑参数
const editParams = ref<EditGroupChatParams>({
    id: route.query.gid as never,
    name: ''
})

// 编辑群名弹层
const namePopup = ref<boolean>(false)

// 编辑群名
const handleEditName = async () => {
    await reqEditGroupChatAPI(editParams.value)
    groupChat.value.name = editParams.value.name as never
    showSuccessToast('编辑群名成功')
    namePopup.value = false
}
// ------------------ 处理编辑群名结束 ------------------



// ------------------ 显示群二维码开始 ------------------
const qrcodePopup = ref<boolean>(false)
const qrCodeText = ref('')
const handleShowQrcode = () => {
    qrCodeText.value = 'sdfasfdf'
    qrcodePopup.value = true
}
// ------------------ 显示群二维码结束 ------------------



// ----------------- 转让管理员功能开始 -----------------
const transferPopup = ref<boolean>(false)
// 候选成员列表
const candidateMemberList = ref<Member[]>([])

// 选中的管理成员
const selectedMember = ref<Member>()

// 显示转让管理员弹层
const handleShowTransferAdmin = () => {
    transferPopup.value = true
}

// 选择候选成员
const handleCheckMember = (member: Member) => {
    candidateMemberList.value.forEach((item: Member) => {
        item.is_admin = 0
    })

    member.is_admin = 1
    selectedMember.value = member
}

// 转让管理员
const handleConfirm = async () => {
    console.log('selectedMember = ', selectedMember.value);
    if (selectedMember.value?.uid == undefined) {
        showToast('请选择群聊成员')
        return false
    }
    
    await reqTransferAdminAPI({gid: route.query.gid as never, member_id: selectedMember.value?.uid as never})
    groupChat.value.member.forEach((item: Member) => {
        if (item.uid == selectedMember.value?.uid) {
            item.is_admin = 1
        } else {
            item.is_admin = 0
        }
    })
    admin.value = {uid: 0, username: '', avatar_url: '', mobile: '', is_admin: 0}
    showSuccessToast('转让成功')
    transferPopup.value = false
}

const handleCancel = () => {
    candidateMemberList.value.forEach((item: Member) => {
        item.is_admin = 0
    })
    transferPopup.value = false
}
// ----------------- 转让管理员功能结束 -----------------



// ------------------- 免打扰功能开始 -------------------
const handleDisturb = async (value: any) => {
    if (route.query.mode == '1') { // 私聊
        await reqDisturbAPI({
            id: friend.value?.id as never,
            uid: friend.value?.uid == userStore.profile.user.uid ? friend.value?.friend_id as never : friend.value?.uid as never,
            is_disturb: value ? 1 : 0
        })
    } else { // 群聊
        await reqGroupChatDisturbAPI({
            id: groupChat.value?.id as never,
            uid: userStore.profile.user.uid,
            is_disturb: value ? 1 : 0
        })
    }
}
// ------------------- 免打扰功能结束 -------------------



// -------------------- 置顶功能开始 --------------------
const handleTop = async (value: any) => {
    if (route.query.mode == '1') { // 私聊
        await reqTopAPI({
            id: friend.value?.id as never,
            uid: friend.value?.uid == userStore.profile.user.uid ? friend.value?.friend_id as never : friend.value?.uid as never,
            is_top: value ? 1 : 0
        })
    } else { // 群聊
        await reqGroupChatTopAPI({
            id: groupChat.value?.id as never,
            uid: userStore.profile.user.uid,
            is_top: value ? 1 : 0
        })
    }
}
// -------------------- 置顶功能结束 --------------------

</script>

<style scoped lang="scss">
page,
.container {
    height: 100vh;

    // 头部信息区域开始
    .user-wrap {
        padding: 60px 0 0 10px;
        background-color: #fff;
        display: flex;
        flex-wrap: wrap;
        .item-box {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 60px;
            height: 80px;
            margin-bottom: 10px;
            margin-right: 20px;
            .avatar {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 60px;
                height: 60px;
                border-radius: 5px;
                overflow: hidden;
                border: 1px solid #cdcdcd;
            }
            .username {
                margin-top: 4px;
                width: 50px;
                font-size: 12px;
                color: #cdcdcd;
            }
            .top {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 60px;
                height: 60px;
                border-radius: 5px;
                overflow: hidden;
                border: 1px dashed #cdcdcd;
                margin-bottom: 18px;
                .icon-jia {
                    font-size: 30px;
                    color: #cdcdcd;
                }
                .icon-jian {
                    font-size: 30px;
                    color: #cdcdcd;
                }
            }
        }
    }

    // 群面板区域开始
    .group-wrap {
        margin-top: 10px;
    }

    // 查询聊天记录开始
    .search-record-wrap {
        margin-top: 10px;
    }

    // 操作区域开始
    .operate-wrap {
        margin-top: 10px;
        .operate-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;
            padding: 15px 10px;
            color: #000;
            border-bottom: 1px solid #f2f2f2;
            .left {
                font-size: 16px;
                flex: 1;
            }
            .right {
                width: 50px;
            }
        }
    }

    // 清空聊天记录开始
    .clear-record-wrap {
        margin-top: 10px;
    }

    // 投诉区域开始
    .complaint-wrap {
        margin-top: 10px;
    }

    // 退出群聊区域开始
    .logout-group-wrap {
        height: 50px;
        line-height: 50px;
        text-align: center;
        margin-top: 20px;
        background-color: #fff;
        color: red;
        
    }

    // 编辑别名弹层区域开始
    .popup-wrap {
        .title-box {
            margin-top: 20px;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px
        }

        .btn-box {
            display: flex;
            justify-content: center;
            margin-top: 5px;
        }

        .member-title-box {
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
            position: fixed;
            left: 0;
            right: 0;
            width: 100%;
            background-color: #27BA9B;
            z-index: 100;
            height: 50px;
            line-height: 50px;
            color: #fff;
        }

        .member-box {
            border-top: 1px solid #cdcdcd;
            padding-top: 50px;
            .member {
                display: flex;
                align-items: center;
                border-bottom: 1px solid #f0f0f0;
                padding: 10px;
                .iconfont {
                    font-size: 25px;
                    color: #f0f0f0;
                }
                .icon-xuanzhong {
                    color: #27BA9B;
                }
                .avatar {
                    width: 60px;
                    height: 60px;
                    border: 1px solid #cdcdcd;

                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-radius: 5px;
                    margin: 0 10px;
                }
                &:last-child {
                    border-bottom: none;
                }
            }
        }

        .member-btn-box {
            display: flex;
            justify-content: space-between;
            padding: 10px 50px;
            border-top: 1px solid #cdcdcd;
            margin-top: 10px;
        }
    }
}
</style>